//
//  NSString+Value.m
//  SLAppProduct
//
//  Created by Jianbo Cai on 2018/4/4.
//  Copyright © 2018年 Sunline. All rights reserved.
//

#import "NSString+Value.h"
#import "NSNumber+StringAdditions.h"

@implementation NSString (Value)

+ (NSString *)isNullToString:(id)string
{
    if ([string isKindOfClass:[NSNull class]] || string == nil || string == NULL) {
        return @"";
    }else if ([string isEqual:@"NULL"] || [string isEqual:[NSNull null]] || [string isEqual:NULL]) {
        return @"";
    }else if ([string isKindOfClass:[NSString class]]) {
        if ([string isEqualToString:@"<null>"] || [string isEqualToString:@"(null)"]) {
            return @"";
        }
    }
    return [NSString stringWithFormat:@"%@",string];
}

- (NSString *)convertToPercentage {
    if ([self isInvalid] || [self isEqualToString:@"--"]) {
        return @"--";
    }
    return [NSString stringWithFormat:@"%0.2f%%",(self.floatValue * 100)];
}

- (NSString *)retainTheDecimalAFew:(NSUInteger)uint {
    if ([self isInvalid] || [self isEqualToString:@"--"]) {
        return @"--";
    }
    NSString *format = [NSString stringWithFormat:@"%%.%ldf",uint];
    return [NSString stringWithFormat:format,self.floatValue];
}

- (NSString *)chineseUnitConversionDecimal:(NSUInteger)uint {
    if ([self isInvalid] || [self isEqualToString:@"--"]) {
        return @"--";
    }
    return [@(self.floatValue) SLChineseStringWithFraction:(int)uint];
}

- (NSString *)serverTimestampConversionWithFormat:(NSString *)format {
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:format];
    NSTimeInterval interval = self.longLongValue / 1000;
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:interval];
    NSString *dateStr = [dateFormatter stringFromDate:date];
    return dateStr;
}

- (NSString *)setDefaultValuesForNull {
    return ([self isInvalid]) ? @"--" : self;
}

- (BOOL)isInvalid {
    return ([self isKindOfClass:[NSString class]] && ([self isEqualToString:@"<null>"] || (self.length == 0)));
}


@end
